<?php

namespace app\admin\controller\agent;

use app\common\controller\Backend;
use think\facade\Db;
use think\facade\Session;
/**
 * 渠道代理
 *
 * @icon fa fa-circle-o
 */
class Agent extends Backend
{
    
    /**
     * Agent模型对象
     * @var \app\admin\model\agent\Agent
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\agent\Agent;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();
            $agent_id=Session::get('admin.agent_id');
            if(!empty($agent_id)){
//                $where['agent_id']=$agent_id;
                $total = $this->model
                    ->where($where)->whereOr('p_agent_id',$agent_id)
                    ->order($sort, $order)
                    ->count();
                $list=$this->model->withCount(['agentCount','userCount'])->where($where)->whereOr('p_agent_id',$agent_id)->select();
            }else{
                $total = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->count();
                $list=$this->model->withCount(['agentCount','userCount'])
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            }
//            dd($list->toArray());
            $list   = $list->toArray();
            $result = ['total' => $total, 'rows' => $list];
            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 查看
     */
    public function agentlist()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags']);
//        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                $list=$this->selectpage();
                return $list;
            }
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();


            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list   = $list->toArray();
            $result = [ 'rows' => $list];

            return json($result);
//        }

        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();

                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace('\\model\\', '\\validate\\', get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name.'.add' : $name) : $this->modelValidate;
                        validate($validate)->scene($this->modelSceneValidate ? 'edit' : $name)->check($params);
                    }
                    $agent_id=Session::get('admin.agent_id');
                    $params['p_agent_id']=$agent_id;
                    $result = $this->model->save($params);
                    $agent_code=$this->getUserCode($this->model->id,6);
                    $this->model->agent_code=$agent_code;
                    $this->model->save();
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        return $this->view->fetch();
    }

    private function getUserCode($value ,$num = 8)
    {
        if($num<1) return '';
        $arrs = ['A','0','B','1','C','2','D','3','E','4','F','5','G','6','H','7','I','8','J','9','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
        $result = $this->getUserCode($value/36 ,--$num ) . $arrs[$value%36];
        return $result;
    }
    
}
